package cn.trigram.json.serializer;

import static java.util.Optional.ofNullable;

import cn.trigram.date.DateUtil;
import cn.trigram.json.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.google.common.base.Strings;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import java.util.TimeZone;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 日期时间的序列化，包括Date和jdk8以后的Temporal类型
 *
 * @version 1.0.0
 * @date 2022/08/23 10:09:09
 * @since 1.0.0
 */
public class TemporalContextualSerializer extends JsonSerializer<Object> implements ContextualSerializer {

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        DateTimeFormat format = ofNullable(property).map(p -> p.getAnnotation(DateTimeFormat.class)).orElse(null);
        final String serializer = Strings.emptyToNull(Optional.ofNullable(format).map(DateTimeFormat::serializer).orElse(null));
        final Class<?> rawClass = ofNullable(property).map(BeanProperty::getType).map(JavaType::getRawClass).orElse(null);
        if (Objects.equals(rawClass, Date.class)) {
            if (Objects.isNull(format)) {
                return new SoftReference<>(new com.fasterxml.jackson.databind.ser.std.DateSerializer().createContextual(prov, property)).get();
            } else {
                return new SoftReference<>(new DateSerializer(format)).get();
            }
        } else {
            if (Objects.equals(rawClass, LocalDate.class)) {
                return new SoftReference<>(new LocalDateSerializer(
                        DateUtil.formatter(ObjectUtils.defaultIfNull(serializer, DateUtil.GF_DEFAULT_SHORT))
                ).createContextual(prov, property)).get();
            } else if (Objects.equals(rawClass, LocalDateTime.class)) {
                return new SoftReference<>(new LocalDateTimeSerializer(
                        DateUtil.formatter(ObjectUtils.defaultIfNull(serializer, DateUtil.GF_DEFAULT_FULL))
                ).createContextual(prov, property)).get();
            } else if (Objects.equals(rawClass, LocalTime.class)) {
                return new SoftReference<>(new LocalTimeSerializer(
                        DateUtil.formatter(ObjectUtils.defaultIfNull(serializer, DateUtil.GF_DEFAULT_TIME))
                ).createContextual(prov, property)).get();
            } else if (Objects.isNull(property)) {
                return new SoftReference<>(new com.fasterxml.jackson.databind.ser.std.DateSerializer().createContextual(prov, property)).get();
            } else {
                return prov.findValueSerializer(rawClass, property);
            }
        }
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) {

    }

    /**
     * @version 1.0.0
     * @date 2022/08/02 16:09:59
     * @since 1.0.0
     */
    @JacksonStdImpl
    public static class DateSerializer extends StdSerializer<Date> {
        private final DateTimeFormat format;

        public DateSerializer(DateTimeFormat format) {
            super(Date.class, false);
            this.format = format;
        }

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            if (Objects.isNull(value)) {
                gen.writeString((String) null);
            }
            final String timezoneStr = this.format.timezone();
            ZoneId zoneId = !StringUtils.equals(timezoneStr, JsonFormat.DEFAULT_TIMEZONE) && StringUtils.isNotBlank(timezoneStr)
                    ? TimeZone.getTimeZone(timezoneStr).toZoneId()
                    : ZoneId.systemDefault();
            gen.writeString(DateUtil.formatter(ObjectUtils.defaultIfNull(Strings.emptyToNull(format.serializer()), DateUtil.GF_DEFAULT_FULL), format.locale(), format.timezone())
                    .format(value.toInstant().atZone(zoneId)));
        }

        @Override
        public void serializeWithType(Date value, JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSer) throws IOException {
            final WritableTypeId typeId = typeSer.writeTypePrefix(gen, typeSer.typeId(value, JsonToken.VALUE_STRING));
            serialize(value, gen, provider);
            typeSer.writeTypeSuffix(gen, typeId);
        }

        @Override
        public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
            return createSchemaNode("string", true);
        }

        @Override
        public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
            visitStringFormat(visitor, typeHint);
        }

    }
}
